package com.fourth_groups.shopping121store.ui.category.myfragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.fourth_groups.shopping121store.Constants;
import com.fourth_groups.shopping121store.R;
import com.fourth_groups.shopping121store.bean.CategoryGroupLeftLvBean;
import com.fourth_groups.shopping121store.http.OkHttpClientUtils;
import com.fourth_groups.shopping121store.ui.category.CategoryFragment;
import com.fourth_groups.shopping121store.ui.category.adapter.CategoryLeftLvAdapter;
import com.fourth_groups.shopping121store.utils.GsonImpl;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 说明：分类界面"全部"的子页面页
 * A simple {@link Fragment} subclass.
 */
public class CategoryAllFragment extends Fragment{
    private List<CategoryGroupLeftLvBean.DataBean.CategoryBean> categoryBeanS = new ArrayList<>();
    private ListView mLvLeft;
    private CategoryLeftLvAdapter myAdapter;
    private static final int SUCCESS = 1;


    //可见列表项的数量
    private int visibleCount = 0;
    //上次点击的位置
    private int lastPosition = 0;
    private int ce = 0;
    //实际列表是否超出屏幕
    private boolean isOut = true;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS:
                    categoryBeanS = (List<CategoryGroupLeftLvBean.DataBean.CategoryBean>) msg.obj;
                    myAdapter = new CategoryLeftLvAdapter(getActivity(),categoryBeanS);
                    mLvLeft.setAdapter(myAdapter);
                    myAdapter.setSelected(0);
                    CategoryGroupLeftLvBean.DataBean.CategoryBean categoryBean = categoryBeanS.get(0);
                    replaseFragment(categoryBean);
                    break;
            }
        }
    };
    private FrameLayout mRightFlContent;


    public CategoryAllFragment() {
        // Required empty public constructor
    }

    private static CategoryAllFragment categoryAllFragment;

    public static Fragment setFragment() {
        if (categoryAllFragment == null)
            synchronized (CategoryFragment.class) {
                if (categoryAllFragment == null) {
                    categoryAllFragment = new CategoryAllFragment();
                }
            }
        return categoryAllFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_category_all, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLvLeft = (ListView) view.findViewById(R.id.all_left_lv);
        mRightFlContent = (FrameLayout) view.findViewById(R.id.all_right_fl);

        mLvLeft.setOnItemClickListener(new MyOnItemClickListener());
        loadData(view);
    }

    private void loadData(View view) {

        OkHttpClientUtils.getDataAsync(view.getContext(), Constants.ALL_GROUP_URL, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    CategoryGroupLeftLvBean bean = GsonImpl.get().toObject(json, CategoryGroupLeftLvBean.class);
                    List<CategoryGroupLeftLvBean.DataBean.CategoryBean> categoryBean = bean.getData().getCategory();
                    Message message = new Message();
                    message.what = SUCCESS;
                    message.obj = categoryBean;
                    mHandler.sendMessage(message);
                }
            }
        },new Object());
    }

    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id)
        {
            //计算滑动
            if(visibleCount == 0)
            {
                visibleCount = mLvLeft.getChildCount();
                if(visibleCount == categoryBeanS.size())
                    isOut = false;
                else
                {
                    ce = visibleCount/2;
                }
            }

            if(position <= (parent.getFirstVisiblePosition() + ce))
            {   //上移
                mLvLeft.smoothScrollToPosition(position - ce);
            }
            else
            {   //下移
                if((parent.getLastVisiblePosition() + ce + 1) <= parent.getCount())
                {
                    mLvLeft.smoothScrollToPosition(position + ce);
                }
                else
                {
                    mLvLeft.smoothScrollToPosition(parent.getCount()-1);
                }
            }

            lastPosition = position;

            myAdapter.setSelected(position);
            myAdapter.notifyDataSetChanged();

            //更新右侧标签页的标题
            CategoryGroupLeftLvBean.DataBean.CategoryBean categoryBean = categoryBeanS.get(position);
            replaseFragment(categoryBean);
        }
    }

    private void replaseFragment(CategoryGroupLeftLvBean.DataBean.CategoryBean categoryBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("bean",categoryBean);
        bundle.putString("flag","all");
        FragmentManager manager = getFragmentManager();
        AllRightFragment fragment = new AllRightFragment();
        fragment.setArguments(bundle);
        manager.beginTransaction().replace(R.id.all_right_fl, fragment).addToBackStack(null).commit();
    }
}
